<?php
namespace app\api\service;
use app\api\model\spec_goods;
use app\BaseController;
use think\facade\Cache;

class CartService extends BaseController
{
    /**
     * 购物车添加商品
     * @return \think\response\Json
     */
    public static function careAdd($u_id,$g_id)
    {
        if (!empty($u_id)){
            $redis = Cache::store('redis');
            $redis->select(9);
//        判断是否存在
            $r1  = $redis->HEXISTS($u_id,$g_id);
            //存在的商品增加1
            if ($r1){
                $redis->hIncrBy($u_id,$g_id,1);
                return json(['code'=>200,'data'=>'','msg'=>'增加成功']);
            }else{
                $redis->hSet($u_id,$g_id,1);
                return json(['code'=>200,'data'=>'','msg'=>'添加商品成功']);
            }
        }else{
            return json(['code'=>500,'data'=>'','msg'=>'请登录']);
        }

    }

    /**
     * @return \think\response\Json
     * 购物车减少物品 以及判断当商品为1件时 减少就是删除
     */
    public static function carerReduce($u_id,$g_id)
    {
        if (!empty($u_id)){
            $redis = Cache::store('redis');
            $value = $redis->hGet($u_id,$g_id);
            if ($value==1){//购物车商品只有一件的时候 减少到0就是删除
                $del_result=  $redis->hDel($u_id,$g_id);
                if($del_result==1) {
                    return json(['code'=>200,'data'=>'','msg'=>'删除成功']);
                }
            }elseif($value>1){
                $redis->hIncrBy($u_id,$g_id,-1);
                return json(['code'=>200,'data'=>'','msg'=>'减少成功']);
            }
        }else{
            return json(['code'=>500,'data'=>'','msg'=>'请登录']);
        }


    }
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 购物车查询列表
     */
    public static function careList($u_id)
    {
        $redis = Cache::store('redis');
        $redis->select(9);
        $data =  $redis->hGetAll($u_id);
        $goods_is = array_keys($data);
        $good = spec_goods::with('goods')->where('id','in', $goods_is)->select()->toArray();
        foreach ($good as $k=>$v){
            static  $goods = [];
            $goods[$k]=$v;
            $id = $v['id'];
            $goods[$k]['order']=$data[$id];
        }
        return json(['code'=>200,'data'=>$goods,'msg'=>'查询成功']);
    }

    /**
     * @return \think\response\Json
     * 购物车的删除
     */
    public static function delelist($u_id,$g_id)
    {
        $redis = Cache::store('redis');
        $redis->select(9);
        $del_result=  $redis->hDel($u_id,$g_id);
        if($del_result==1) {
            return json(['code'=>200,'data'=>'','msg'=>'删除成功']);
        }
    }
}